package com.demo.utils;

import org.apache.commons.net.ftp.FTPClient;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * Created by Administrator on 2016/12/13.
 */
public class FTPUtil {
    /**
     * 登录ftp
     *
     * @param hostIP
     * @param port
     * @param userName
     * @param password
     * @param ftpClient
     * @return
     * @throws IOException
     */
    public static boolean loginFTP(String hostIP, int port, String userName, String password, FTPClient ftpClient) throws IOException {
        ftpClient.connect(hostIP, port);
        return ftpClient.login(userName, password);
    }

    /**
     * 退出ftp
     *
     * @param ftpClient
     * @throws IOException
     */
    public static void logoutFTP(FTPClient ftpClient) throws IOException {
        if (ftpClient != null) {
            ftpClient.logout();
            ftpClient.disconnect();
        }
    }

    /**
     * 用于单个文件上传使用
     *
     * @param file
     * @param hostIP
     * @param port
     * @param userName
     * @param password
     * @param path
     * @return
     * @throws IOException
     */
    public static boolean upload(File file, String hostIP, int port, String userName, String password, String... path) throws IOException {
        boolean f = false;
        FTPClient ftpClient = new FTPClient();
        if (!loginFTP(hostIP, port, userName, password, ftpClient)) throw new IOException("login ftp fail");
        ftpClient.changeWorkingDirectory("/");
        for (String p : path) {
            if (!ftpClient.changeWorkingDirectory(p)) {
                ftpClient.makeDirectory(p);
                ftpClient.changeWorkingDirectory(p);
            }
        }
        f = ftpClient.storeFile(file.getName(), new FileInputStream(file));
        logoutFTP(ftpClient);
        return f;

    }

    /**
     * 用于批量上传时使用
     *
     * @param ftpClient
     * @param file
     * @param path
     * @return
     * @throws IOException
     */
    public static boolean upload(FTPClient ftpClient, File file, String[] path) throws IOException {
        if (ftpClient == null || !ftpClient.isAvailable()) {
            return false;
        }
        ftpClient.changeWorkingDirectory("/");
        for (String p : path) {
            if (!ftpClient.changeWorkingDirectory(p)) {
                ftpClient.makeDirectory(p);
                ftpClient.changeWorkingDirectory(p);
            }
        }
        return ftpClient.storeFile(file.getName(), new FileInputStream(file));
    }

}
